package cn.nhic.web.controller;/**
 * Created by duweiping on 2024/9/3 22:57
 */

import cn.nhic.web.common.HtmlUtils;
import cn.nhic.web.constant.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author duweiping
 * @date 2024/9/3 22:57
 * <p>
 * 学习目标：
 * 1. 注意WebServlet注解的作用，让写代码很方便
 * 2. 如何获取请求中的值。
 *
 * todo 大家思考一下：每一个servlet，最后都会生成一个html文档，如何设计会更好？
 */
@WebServlet(urlPatterns = "/i_read_http_header_value")
public class WebServletInterfaceWeb extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType(Constants.DOC_FORMAT_TYPE);

        StringBuilder builder = HtmlUtils.generateHtmlHead("read http header  value");

        builder.append("<body>");

        Enumeration<String> headerNames = req.getHeaderNames();
        Map<String, String> headerKeyValueMap = new LinkedHashMap<>();

        if (headerNames == null) {
            String body = "<body><p>http header 为空值</p></body>";
            builder.append(body);
        } else {
            headerKeyValueMap.put("<strong> http header key</strong>", "<strong>http header value</strong>");
            while (headerNames.hasMoreElements()) {
                String headerKey = headerNames.nextElement();
                String headerValue = req.getHeader(headerKey);
                headerKeyValueMap.put(headerKey, headerValue);
            }
        }

        // todo 其实整体生成一个html文档，有比较优秀的设计。
        if (!headerKeyValueMap.isEmpty()) {
            builder.append("<table>");
            // map 转表格
            for (Map.Entry<String, String> entry : headerKeyValueMap.entrySet()) {
                builder.append("<tr><td>").append(entry.getKey()).append("</td><td>")
                        .append(entry.getValue()).append("</td>").append("</tr>");
            }
            builder.append("</table>");
        }

        builder.append("</body>");
        builder.append("</html>");

        PrintWriter out = resp.getWriter();
        out.println(builder.toString());

    }
}
